package com.dk.service.impl;

import com.alibaba.fastjson.JSON;
import com.dk.pojo.CarBrand;
import com.dk.mapper.CarBrandMapper;
import com.dk.service.CarBrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张成涛
 * @since 2021-08-12
 */
@Service
public class CarBrandServiceImpl extends ServiceImpl<CarBrandMapper, CarBrand> implements CarBrandService {

    @Autowired
    private CarBrandMapper carBrandMapper;
    @Autowired
    public RestHighLevelClient restHighLevelClient;
    @Override
    public List<CarBrand> toSelect() {
        return carBrandMapper.selectList(null);
    }

    @Override
    public List<Map<String, Object>> searchBySkuName(String brandName) throws IOException {


        // 1.创建查询请求对象
        SearchRequest searchRequest = new SearchRequest("car_brand");

        // 2.构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // (1)查询条件 使用QueryBuilders工具类创建
        // 精确查询
        // TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", keyword);
        // 匹配查询
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("brand_name", brandName);

        // (2)其他<可有可无>：（可以参考 SearchSourceBuilder 的字段部分）
        // 设置高亮
 /*       HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("goods_name");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);*/
        // // 分页
//        searchSourceBuilder.from(pageIndex);
//        searchSourceBuilder.size(pageSize);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        // (3)条件投入
        searchSourceBuilder.query(matchQueryBuilder);

        // 3.添加条件到请求
        searchRequest.source(searchSourceBuilder);

        // 4.客户端查询请求
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        // 5.查看返回结果
        SearchHits hits = search.getHits();
        System.out.println(JSON.toJSONString(hits));
        System.out.println("=======================");
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit documentFields : hits.getHits()) {
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();//获取高亮字段
            HighlightField name = highlightFields.get("brand_name"); //获取被加上标签的那个值
            //替换
            if (name != null) {
                Text[] fragments = name.getFragments();
                StringBuilder stringBuilder = new StringBuilder();
                for (Text fragment : fragments) {
                    stringBuilder.append(fragment);
                }
                sourceAsMap.put("brand_name", stringBuilder.toString());
            }
            list.add(sourceAsMap);
            System.out.println(sourceAsMap);
        }
        return list;
    }
}
